package com.cote.douhahou.pretloan.msg.widget;

import android.Manifest;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.camera.core.CameraSelector;
import androidx.camera.core.ImageCapture;
import androidx.camera.core.ImageCaptureException;
import androidx.camera.core.Preview;
import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.camera.view.PreviewView;
import androidx.core.content.ContextCompat;
import androidx.exifinterface.media.ExifInterface;
import androidx.fragment.app.FragmentActivity;

import com.cote.douhahou.pretloan.utils.image_akomapalend.ImageConvert;
import com.google.common.util.concurrent.ListenableFuture;
import com.cote.douhahou.pretloan.beans.OtheAkomapalendrsInfo;
import com.cote.douhahou.pretloan.beans.ProcesAkomapalendsInfoData;
import com.cote.douhahou.pretloan.launcher.BaseContext;
import com.cote.douhahou.pretloan.network.HttpHelper;
import com.cote.douhahou.pretloan.utils.AkomapaLendUtil;
import com.cote.douhahou.pretloan.R;
import com.cote.douhahou.pretloan.utils.AkomapaLendConfigs;

import java.io.File;
import java.io.IOException;
import java.util.TreeMap;

import pub.devrel.easypermissions.EasyPermissions;


public class FaceAkomapalendViewManager extends BaseProcAkomapalendessWidgetManager {

    private final FragmentActivity acti_akomapalendvity;

    private PreviewView previe_akomapalendwView;
    private ImageButton imag_akomapalendeIb;
    private ImageButton photog_akomapalendraphIb;

    private String pho_akomapalendtoUrl;

    private ListenableFuture<ProcessCameraProvider> processCameraProvid_akomapalenderListenableFuture;

    private ImageCapture imageCap_akomapalendture;

    private String imgP_akomapalendath = "";

    private Runnable afterPermis_akomapalendsionRunnable;

    private Bitmap imageB_akomapalenditmap;

    private final Runnable processResp_akomapalendRunnable, imgUploadRe_akomapalendsp;

    public FaceAkomapalendViewManager(View view, ProcesAkomapalendsInfoData data, String page, Runnable processRespRunnable, Runnable imgUploadResp){
        super(view,data,page);
        this.acti_akomapalendvity = (FragmentActivity) view.getContext();
        this.processResp_akomapalendRunnable = processRespRunnable;
        this.imgUploadRe_akomapalendsp = imgUploadResp;
    }

    @Override
    protected void in_akomapalendit(){

        previe_akomapalendwView = mVi_akomapalendew.findViewById(R.id.ipfa_view_preview);
        imag_akomapalendeIb = mVi_akomapalendew.findViewById(R.id.ipfa_ib_image);
        photog_akomapalendraphIb = mVi_akomapalendew.findViewById(R.id.ipfa_ib_photograph);

        //开始人脸拍照点击
        imag_akomapalendeIb.setOnClickListener(v -> runAfterChe_akomapalendckCameraPermis_akomapalendsion(this::startPh_akomapalendotograph));

        //拍照点击
        photog_akomapalendraphIb.setOnClickListener(v -> {
            runAfterChe_akomapalendckCameraPermis_akomapalendsion(() -> {
                if (!TextUtils.isEmpty(pho_akomapalendtoUrl)) startPh_akomapalendotograph();
                else captur_akomapalendeImage();
            });
        });

    }

    @Override
    public boolean checkI_akomapalendnput() {
        return false;
    }

    @Override
    public String getInp_akomapalendut() {
        return "";
    }

    public void nextCl_akomapalendick(String path){

        runAfterChe_akomapalendckCameraPermis_akomapalendsion(() -> {
            if (TextUtils.isEmpty(pho_akomapalendtoUrl)) startPh_akomapalendotograph();//No 照片时自动开启拍照
            else
                HttpHelper.inst().processSubmit(
                        acti_akomapalendvity,
                        path,
                        new TreeMap<String, String>() {{put("faceImgUrl", pho_akomapalendtoUrl);}},
                        () -> HttpHelper.inst().process(acti_akomapalendvity,() -> {if (processResp_akomapalendRunnable !=null) processResp_akomapalendRunnable.run();}
                    )
                );

        });
    }

    private void startPh_akomapalendotograph(){

        try {
            HttpHelper.inst().submitEvent(pa_akomapalendge,"START_TAKING_CLICK","");

            pho_akomapalendtoUrl = "";

            //打开拍照
            processCameraProvid_akomapalenderListenableFuture = ProcessCameraProvider.getInstance(mVi_akomapalendew.getContext());
            //监听摄像头的启动
            processCameraProvid_akomapalenderListenableFuture.addListener(() -> {
                try {
                    ProcessCameraProvider provider = processCameraProvid_akomapalenderListenableFuture.get();

                    previe_akomapalendwView.setVisibility(View.VISIBLE);

                    //释放资源
                    provider.unbindAll();

                    //创建相机选择器并选择前置摄像头
                    CameraSelector cameraSelector = new CameraSelector.Builder()
                            .requireLensFacing(CameraSelector.LENS_FACING_FRONT)
                            .build();

                    //创建一个相机预览对象并将其与PreviewView的SurfaceProvider绑定，实现在该组件上显示相机预览画面
                    Preview preview = new Preview.Builder().build();
                    preview.setSurfaceProvider(previe_akomapalendwView.getSurfaceProvider());

                    //创建一个ImageCapture对象用于拍摄照片，设置拍照模式为最小化延迟模式
                    imageCap_akomapalendture = new ImageCapture.Builder()
                            .setCaptureMode(ImageCapture.CAPTURE_MODE_MINIMIZE_LATENCY)
                            .build();

                    //点击图像隐藏,拍照按键显示
                    imag_akomapalendeIb.setImageBitmap(null);
                    photog_akomapalendraphIb.setVisibility(View.VISIBLE);

                    //启动相机并将其与当前生命周期绑定  cameraSelector用于选择相机设备，preview用于显示预览。imageCapture用于捕获图像
                    if (acti_akomapalendvity !=null) provider.bindToLifecycle(acti_akomapalendvity, cameraSelector, preview, imageCap_akomapalendture);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }, ContextCompat.getMainExecutor(mVi_akomapalendew.getContext()));
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    //拍照
    private void captur_akomapalendeImage() {

        HttpHelper.inst().submitEvent(pa_akomapalendge,"TAKING_PICTURE","");

        imgP_akomapalendath = this.getImag_akomapalendeFi_akomapalendlePath();
        ImageCapture.OutputFileOptions options = new ImageCapture.OutputFileOptions.Builder(new File(imgP_akomapalendath)).build();
        imageCap_akomapalendture.takePicture(
                options,
                ContextCompat.getMainExecutor(mVi_akomapalendew.getContext()),
                new ImageCapture.OnImageSavedCallback() {
                    @Override
                    public void onImageSaved(@NonNull ImageCapture.OutputFileResults outputFileResults) {
                        try {
                            Bitmap bitmap = BitmapFactory.decodeFile(imgP_akomapalendath);
                            imageB_akomapalenditmap = rotateBi_akomapalendtmap(bitmap, imgP_akomapalendath);

                            if (!TextUtils.isEmpty(imgP_akomapalendath)) {
                                //照片压缩
                                ImageConvert.startConvertImage(
                                        new File(imgP_akomapalendath),
                                        (localPath, thumpImg) -> {
                                            imageB_akomapalenditmap = thumpImg;
                                            //上传照片
                                            new Thread(() -> HttpHelper.inst().saveImage(acti_akomapalendvity,localPath,() -> {
                                                if (imgUploadRe_akomapalendsp !=null) imgUploadRe_akomapalendsp.run();
                                            })).start();
                                        }
                                );
                            } else {
                                pho_akomapalendtoUrl = null;
                                Toast.makeText(mVi_akomapalendew.getContext(), mVi_akomapalendew.getContext().getString(R.string.tips_upload_photo_again),Toast.LENGTH_SHORT).show();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    @Override
                    public void onError(@NonNull ImageCaptureException exception) {
                        Toast.makeText(mVi_akomapalendew.getContext(),"Error: " + exception.getMessage(),Toast.LENGTH_SHORT).show();
                    }
                }
        );

    }

    public void onPhotoUplo_akomapalendadRespo_akomapalendnse() {

        String imagePath = OtheAkomapalendrsInfo.instance().getImgPath_akomapalend();

        if (TextUtils.isEmpty(imagePath)) {
            Toast.makeText(mVi_akomapalendew.getContext(), mVi_akomapalendew.getContext().getString(R.string.tips_upload_photo_again),Toast.LENGTH_SHORT).show();
            return;
        }

        this.pho_akomapalendtoUrl = imagePath;

        imag_akomapalendeIb.setImageBitmap(imageB_akomapalenditmap);
        previe_akomapalendwView.setVisibility(View.GONE);
    }

    /**
     * 根据角度反转图片
     */
    public static Bitmap rotateBi_akomapalendtmap(Bitmap bitmap, String imageFilePath) {
        try {

            ExifInterface exif = new ExifInterface(imageFilePath);
            int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);
            Matrix matrix = new Matrix();

            switch (orientation) {
                case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
                    matrix.setScale(-1, 1);
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    matrix.setRotate(180);
                    break;
                case ExifInterface.ORIENTATION_FLIP_VERTICAL:
                    matrix.setRotate(180);
                    matrix.postScale(-1, 1);
                    break;
                case ExifInterface.ORIENTATION_TRANSPOSE:
                    matrix.setRotate(90);
                    matrix.postScale(-1, 1);
                    break;
                case ExifInterface.ORIENTATION_ROTATE_90:
                    matrix.setRotate(90);
                    break;
                case ExifInterface.ORIENTATION_TRANSVERSE:
                    matrix.setRotate(-90);
                    matrix.postScale(-1, 1);
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    matrix.setRotate(180);
                    break;
                default:
                    return bitmap;
            }

            try {
                Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
                bitmap.recycle();
                return rotatedBitmap;
            } catch (OutOfMemoryError e) {
                e.printStackTrace();
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    //执行前判断相机Permission
    public void runAfterChe_akomapalendckCameraPermis_akomapalendsion(Runnable runnable){
        if (!AkomapaLendUtil.permissionsHasAgree(mVi_akomapalendew.getContext(), Manifest.permission.CAMERA)) {
            afterPermis_akomapalendsionRunnable = runnable;
            if (acti_akomapalendvity !=null)
                EasyPermissions.requestPermissions(acti_akomapalendvity, mVi_akomapalendew.getContext().getString(R.string.request_permission_camera), AkomapaLendConfigs.PermissionCCamera, Manifest.permission.CAMERA);
        } else if (runnable!=null) runnable.run();

    }

    /**
     * 获取图片路径
     */
    private String getImag_akomapalendeFi_akomapalendlePath() {
        String pictureId = System.currentTimeMillis() + "";
        String imgDir = getSandb_akomapalendoxFolderPa_akomapalendth();
        return (imgDir + File.separator + pictureId + ".jpg");
    }

    /**
     * 获取沙盒路径
     */
    private String getSandb_akomapalendoxFolderPa_akomapalendth() {
        String inAppFolder = BaseContext.instance().getFilesDir().getAbsolutePath();
        inAppFolder += File.separator;
        inAppFolder += AkomapaLendConfigs.MyProduct;
        inAppFolder += "_PICS";

        File folderFile = new File(inAppFolder);
        if (!folderFile.exists()) {
            folderFile.mkdirs();
        }

        return inAppFolder;
    }

    public void onCameraPer_akomapalendmission_akomapalendAgree(){
        if (afterPermis_akomapalendsionRunnable !=null) afterPermis_akomapalendsionRunnable.run();
    }

}
